package top.yehot.kettle.boot.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.jfree.util.Log;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import top.yehot.cmm.util.core.base.BaseException;
import top.yehot.cmm.util.spring.anns.ResponseResult;
import top.yehot.kettle.boot.core.SysConst;
import top.yehot.kettle.boot.models.vo.task.TaskRecordSearchVO;
import top.yehot.kettle.boot.models.vo.task.TaskRecordVO;
import top.yehot.kettle.boot.service.TaskRecordService;

/**
 * 任务日志管理
 * 
 * @author lquan
 * @date 2022年6月5日 下午3:18:51
 */
@Api(tags = "任务日志管理")
@RestController
@RequestMapping(SysConst.VERSION + "/task-record")
@AllArgsConstructor
@ResponseResult
public class TaskRecordController {
	
	private final TaskRecordService taskRecordService;

	@ApiOperation("任务日志列表（分页）")
	@PostMapping("page")
	public IPage<TaskRecordVO> page(@RequestBody TaskRecordSearchVO param) {
		return taskRecordService.page(param);
	}
	
	@ApiOperation("任务日志文件下载")
	@GetMapping("download")
	public void download(@RequestParam("filePath") String filePath, HttpServletResponse response) {
		BufferedInputStream bis = null;
		OutputStream outputStream = null;
		try {
			File file = new File(filePath);
			
			// 重置response
	        response.reset();
	        // ContentType，即告诉客户端所发送的数据属于什么类型
	        response.setContentType("application/octet-stream; charset=UTF-8");
	        // 获得文件的长度
	        response.setHeader("Content-Length", String.valueOf(file.length()));
	        // 设置编码格式
	        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
			
	        bis = new BufferedInputStream(new FileInputStream(file));
	        outputStream = response.getOutputStream();
	        
	        byte[] buff = new byte[2048];
	        int i = 0;
	        while((i = bis.read(buff)) != -1) {
	        	outputStream.write(buff, 0, i);
	        	outputStream.flush();
	        }
		} catch (Exception e) {
			throw new BaseException(e);
		} finally {
			try {
				if (null != bis) bis.close();
				if (null != outputStream) outputStream.close();
			} catch (Exception e2) {
				Log.error("关闭 BufferedInputStream 失败", e2);
			}
		}
	}
	
}
